<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminRole;
use App\Models\AdminMenu;
use App\Helpers\Common;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class AdminRoleController extends BaseController
{

    public function initialize(Request $request)
    {
        parent::initialize($request);

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere[] = ['status', '<>', 90];
        $this->defaultWhere = $defaultWhere;
    }

    /**
     * Save Post
     */
    protected function savePost($request)
    {
        $className = '\\App\\Models\\' . $this->model;
        $model = new $className;

        if ($request->post()) {
            try {
                $data = self::evalData($request);
                $data['access'] = implode(',', $data['access']);

                if ($data['id']) {
                    // Update
                    $data['updated_at'] = time();
                    $result = $model->where('id', $data['id'])->update($data);

                    $msg = '保存成功!';
                    $logInfo = $this->admin->name . '更新了一条' . __($this->model) . '数据。';
                } else {
                    // Insert
                    $data['created_id'] = $data['updated_id'] = $this->admin->id;
                    $data['created_at'] = time();
                    $result = $model->create($data);

                    $msg = '添加成功!';
                    $logInfo = $this->admin->name . '添加了一条' . __($this->model) . '数据。';
                }

                if ($result === false) {
                    return response()->json([
                        'code' => 0,
                        'msg' => $msg
                    ]);
                }

                // 写入日志
                Common::adminLog($request, $logInfo);

                return response()->json([
                    'code' => 1,
                    'msg' => $msg
                ]);
            } catch (Exception $e) {
                return response()->json([
                    'code' => 0,
                    'msg' => $e->getMessage()
                ]);
            }
        }
    }

    /**
     * Delete
     */
    public function delete(Request $request, $id)
    {
        $className = '\\App\\Models\\' . $this->model;
        $model = new $className;

        // 是否被使用
        $usedInfo = $this->isUsed($id);
        if ($usedInfo['code'] == 0) {
            return response()->json([
                'code' => 0,
                'msg' => $usedInfo['msg']
            ]);
        }
        if ($usedInfo['code'] == 1) {
            $result = $model->where('id', $id)->delete();
        } elseif ($usedInfo['code'] == 2) {
            $result = $model->where('id', $id)->update(['deleted_id' => $this->admin->id, 'deleted_at' =>time(), 'status' => 90]);
        }
        if ($result === false) {
            return response()->json([
                'code' => 0,
                'msg' => '删除失败'
            ]);
        }

        // 写入日志
        $logInfo = $this->admin->name . '删除了一条' . __($this->model) . '数据。';
        Common::adminLog($request, $logInfo);

        return response()->json([
            'code' => 1,
            'msg' => '删除成功!'
        ]);
    }

    /**
     * 权限
     */
    public function getMenus(Request $request)
    {
        $param = $request->all();

        $access = [];
        if (isset($param['id'])) {
            $roleId = $param['id'];
            $access = AdminRole::where('id', $roleId)->get('access')->toArray();
            $access = explode(',', $access[0]['access']);
        }

        $list = [];
        $recursive = function ($parentId) use (&$recursive, &$list, $access) {
            $where = [
                ['parent_id', '=', $parentId],
                ['status', '=', 1]
            ];
            $menus = AdminMenu::where($where)->select('id', 'name as title', 'parent_id')->orderBy('sorting', 'ASC')->get()->toArray();
            foreach ($menus as $key => &$menu) {
                //$menu['spread'] = true; // 节点是否初始展开
                $menu['field'] = 'access[]';
                if (in_array($menu['id'], $access)) {
                    $menu['checked'] = true;
                }

                // 下级菜单
                $menu['children'] = $recursive($menu['id']);
                if ($parentId == 0) {
                    $list[] = $menu;
                }
            }

            return $menus;
        };

        $recursive(0);

        return response()->json($list);
    }

    /**
     * 是否被使用过
     */
    protected function isUsed($id)
    {
        if (!$id) {
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 是否有管理员
        $admin = \App\Models\AdminRoleUser::where('role_id', $id)->select('id')->first();
        if ($admin) {
            return ['code' => 0, 'msg' => '该角色下有管理员，请先删除管理员'];
        }

        return ['code' => 1, 'msg' => ''];
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['name']) && $param['name']) {
            $where[] = ['name', 'like', '%' . trim($param['name']) . '%'];
        }
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = explode(' ~ ', $param['range_date']);
            $where[] = ['created_at', '>=', strtolower($rangeDate[0])];
            $where[] = ['created_at', '<=', strtotime($rangeDate[1])];
        }

        return $where;
    }
}
